package yt.demo.appcommontools.utils;

import cn.hutool.crypto.digest.DigestUtil;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

@Component
public class FileUtils {


    public static String getFileExtension(String fileName) {
        int dotIndex = fileName.lastIndexOf('.');
        return (dotIndex > 0 && dotIndex < fileName.length() - 1) ? fileName.substring(dotIndex + 1) : "";
    }

    public static String formatFileSize(Long bytes) {
        if (bytes < 1024) {
            return bytes + " B";
        } else if (bytes < 1048576) {
            return String.format("%.2fKB", bytes / 1024.0);
        } else if (bytes < 1073741824) {
            return String.format("%.2fMB", bytes / 1048576.0);
        } else {
            return String.format("%.2fGB", bytes / 1073741824.0);
        }
    }

    public static String removeLeadingDot(String filePath) {
        // 检查路径是否以 '.' 开头
        if (filePath.startsWith(".")) {
            return filePath.substring(1); // 去掉开头的 '.'
        }
        return filePath; // 如果没有开头的 '.', 返回原路径
    }


    public static String calculateFileHash(String originalFileName) {
        return DigestUtil.md5Hex(originalFileName); // 返回 MD5 哈希值的十六进制表示
    }

    public static String getFilePath() {
        LocalDate currentDate = LocalDate.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        return currentDate.format(formatter);
    }

    public static String getBase64MimeType(String base64Data) {
        String[] parts = base64Data.split(",");
        if (parts.length > 0) {
            String mimePart = parts[0];
            return mimePart.split(":")[1].split(";")[0]; // 获取 MIME 类型
        }
        throw new IllegalArgumentException("Invalid base64 data");
    }



    public static String getFileExtensionFromMimeType(String mimeType) {
        switch (mimeType) {
            case "image/jpeg":
                return "jpg";
            case "image/png":
                return "png";
            case "image/gif":
                return "gif";
            case "application/pdf":
                return "pdf";
            // 添加更多 MIME 类型的映射
            default:
                throw new IllegalArgumentException("Unsupported MIME type: " + mimeType);
        }
    }

}
